/**
 * 
 */
package it.unibo.refolding.common;

import java.io.Serializable;
import java.util.Collection;

import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class DoublePair implements Comparable<DoublePair>, Serializable {

	private static final long serialVersionUID = 851702665690085751L;
	
	public static final DoublePair[] EMPTY_ARRAY = new DoublePair[0];

	public DoublePair(double x, double y) {
		this.x = x;
		this.y = y;
	}

	public static DoublePair of(double x, double y) {
		return new DoublePair(x, y);
	}

	public int compareTo(DoublePair other) {
		int cmp = Double.compare(x, other.x);
		if (cmp == 0) {
			cmp = Double.compare(y, other.y);
		}
		return cmp;
	}

	public final double x, y;

	@Override
	public String toString() {
		return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(x).append(y).toHashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof DoublePair)) {
			return false;
		}
		DoublePair other = (DoublePair) obj;
		return Double.doubleToLongBits(x) == Double.doubleToLongBits(other.x)
				&& Double.doubleToLongBits(y) == Double.doubleToLongBits(other.y);
	}

	public static double sumX(DoublePair[] tz) {
		double sum = 0;
		for (DoublePair dp : tz) {
			sum += dp.x;
		}
		return sum;
	}

	public static double[] x(DoublePair[] tz) {
		double[] a = new double[tz.length];
		for (int i = tz.length; --i >= 0;) {
			a[i] = tz[i].x;
		}
		return a;
	}

    public static double[] y(DoublePair[] tz) {
        double[] a = new double[tz.length];
        for (int i = tz.length; --i >= 0;) {
            a[i] = tz[i].y;
        }
        return a;
    }

    public static double[] x(Collection<DoublePair> tz) {
        double[] a = new double[tz.size()];
        int i = 0;
        for (DoublePair dp : tz) {
            a[i++] = dp.x;
        }
        return a;
    }

    public static double[] y(Collection<DoublePair> tz) {
        double[] a = new double[tz.size()];
        int i = 0;
        for (DoublePair dp : tz) {
            a[i++] = dp.y;
        }
        return a;
    }
}
